local skynet = require "skynet"
local proxypack = require "proxypack"
local redis = require "skynet.db.redis"
local server_config = dofile(skynet.getenv("server_config"))

local table_insert = table.insert
local table_unpack = table.unpack

local data_workers = {}
local CMD = {}

local function init(worker_num)
	-- local conf = {
	-- 	redis_host = server_config.redis_conf.host,
	-- 	redis_port = tonumber(server_config.redis_conf.port),
	-- 	redis_db = tonumber(server_config.redis_conf.db),
	-- 	redis_auth = server_config.redis_conf.auth,
		
	-- 	dirty_queue_db = tonumber(server_config.redis_conf.dirty_queue_db),
	-- 	dirty_queue_key = server_config.redis_conf.dirty_queue_key,
	-- 	pre_alloc = tonumber(skynet.getenv "pre_alloc"),
	-- 	max_cache_connection_num = tonumber(skynet.getenv "max_cache_connection_num"),

	-- 	db_host = server_config.mongo_base_conf.host,
	-- 	db_port = tonumber(server_config.mongo_base_conf.port),
	-- 	db_name = server_config.mongo_base_conf.dbname,
	-- 	db_coll_name = server_config.mongo_base_conf.collname,
	-- }
	
	for i = 1,worker_num do
		local worker = skynet.newservice('data_worker')
		skynet.call(worker,'lua','open')
		table.insert(data_workers,worker)
	end
end

function CMD.start()
	local worker_num = tonumber(skynet.getenv("data_worker_num")) or 8
	
	init(worker_num)

	print('start.... worker num is ',worker_num)
	skynet.dispatch('lua',function(session,source,cmd,uid,...)
		local i = uid % #data_workers + 1
		skynet.redirect(data_workers[i], source, 'lua', session, skynet.pack(cmd, uid, ...))
		skynet.ignoreret()
		-- local r = {skynet.call(data_workers[i],'lua',cmd,uid,...)}
		-- if #r > 0 then
		-- 	skynet.retpack(table_unpack(r))
		-- end
	end)

	skynet.retpack(true)
end

skynet.start(function()
	skynet.dispatch("lua", function(session,source,action,...)
		CMD[action](...)
	end)
end)
